#coding: utf8

import sys
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)

from gevent import server,pool,spawn,monkey
monkey.patch_all()

import time
import pymongo
import json

import logging
import logging.config

from exceptions import Exception
from itemsimilar import correl

logging.config.fileConfig('./conf/log.conf')
rlog = logging.getLogger('root')

catsdata = json.load(open('invert.cat.json'))

def spawn_correl(nick):
    rlog.info('recommander processing for nick: %s' %(repr(nick)))
    m = pymongo.Connection(port=57324)
    correl(nick, m.taogold, catsdata)

def srv_handle(socket, address):
    ct = socket.recv(1024)
    while not ct.endswith('\n\n'):
        ct += socket.recv(1024)
    try:
        u = json.loads(ct)
    except Exception as e:
        rlog.warning('parse json[%s] fail: %s' %(repr(ct), repr(e)))
        socket.send('fail\n\n')
        socket.close()
        return
    if 'nick' not in u:
        rlog.warning('wrong data: %s' %(repr(ct)))
        socket.send('fail\n\n')
    else:
        spawn(spawn_correl, u['nick'])
        socket.send('success\n\n')
    socket.close()

def srv():
    srv = server.StreamServer(('127.0.0.1', 8500), srv_handle)
    srv.serve_forever()

def main():
    try:
        pid = os.fork() 
        if pid>0:
            sys.exit(0)
    except Exception as e:
        sys.exit('fork #1 error: %s' %(str(e)))
    try:
        pid = os.fork() 
        if pid>0: 
            sys.exit(0)
    except Exception as e:
        sys.exit('fork #2 error: %s' %(str(e)))
    pid=os.getpid()
    fw = open('status/isimsrv.pid', 'w')
    fw.write(str(pid))
    fw.close()
    srv()

if __name__ == '__main__':
    #testing_shop_rec('miaowanghuan')
    #testing_shop_rec('古代')
    main()





